package com.weido.nettyServer.core;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.io.UnsupportedEncodingException;

/**
 * Created by chenli on 2019/11/12.
 */
public class HttpResponse {
    //SocketChannel的封装
    private ChannelHandlerContext ctx;

    private FullHttpRequest req;

    public HttpResponse(ChannelHandlerContext ctx, FullHttpRequest req) {
        this.ctx = ctx;
        this.req = req;
    }


    public void writeError(String out, HttpResponseStatus status) {
        if (out == null || out.length() == 0) {
            out = "";
        }
        try {
            FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    status,
                    // 将输出值写出 编码为UTF-8
                    Unpooled.wrappedBuffer(out.getBytes("UTF-16")));
            fullHttpResponse.headers().set("Content-Type", "text/html;");
            ctx.write(fullHttpResponse);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            ctx.flush();
            ctx.close();

        }

    }

    public void write(String out) {
        if (out == null || out.length() == 0) {
            out = "";
        }
        try {
            FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    // 将输出值写出 编码为UTF-8
                    Unpooled.wrappedBuffer(out.getBytes("UTF-16")));
            fullHttpResponse.headers().set("Content-Type", "text/html;");
            ctx.write(fullHttpResponse);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            ctx.flush();
            ctx.close();

        }
    }
}

